<script setup>
//import {excelApi} from "../../../api/axios";
//import {MINIO_HOST} from "../../../const";
import {onMounted, ref, shallowReactive, shallowRef} from "vue";
import router from "../../../router";
import {ElMessage} from "element-plus";
import {dateFormat, myRemove, myPage, myRemoveBatch, LOCAL_RES} from "../../../util";
import {genderFormat, getResponseData, elConfirm} from "../../../util";
import {pageApi, removeApi, removeBatchApi} from "../../../api/emp.js";
import {resetPasswdApi, UPLOAD_AVATAR_URL} from "../../../api/emp.js";
import {listApi} from "../../../api/dept.js";
import MyNav from "../../../components/MyNav.vue";
import MyHead from "../../../components/MyHead.vue";
import MyTable from "../../../components/MyTable.vue";
import MyPager from "../../../components/MyPager.vue";
import MyList from "../../../components/MyList.vue";

// 获取当前登录的员工
let loginEmp = JSON.parse(sessionStorage.getItem('loginEmp'));

/* ==================== 分页查询 ==================== */
// 表格数据 + 分页数据
let records = ref();
let pageInfo = shallowReactive({'pageNum': 1, 'pageSize': 5, 'fn': page});
// 分页查询条件字段：员工姓名，员工电话，员工所在部门ID
let empName = shallowRef();
let empPhone = shallowRef();
let empDeptId = shallowRef();

// 分页函数
async function page(pageNum = pageInfo['pageNum'], pageSize = pageInfo['pageSize']) {

  // 分页基础配置
  let config = {
    'api': pageApi,
    'params': {'pageNum': pageNum, 'pageSize': pageSize},
    'records': records,
    'pageInfo': pageInfo
  }

  // 附加为分页条件
  if (empName.value) config['params']['name'] = empName.value;
  if (empPhone.value) config['params']['phone'] = empPhone.value;
  if (empDeptId.value) config['params']['deptId'] = empDeptId.value;

  // 发送分页请求
  await myPage(config);
}

/* ==================== 查看详情 ==================== */
// 员工详情抽屉 + 员工详情列表数据
let detailDrawer = shallowRef();
let detailItems = ref();

function detail(record) {
  detailItems.value = [
    {'label': '员工头像', 'value': record['avatar'], 'type': 'img', 'minio': minio},
    {'label': '员工姓名', 'value': record['name']},
    {'label': '员工编号', 'value': record['eno'], 'type': 'tag'},
    {'label': '员工性别', 'value': record['gender'], 'format': genderFormat},
    {'label': '手机号码', 'value': record['phone']},
    {'label': '微信号码', 'value': record['wechat']},
    {'label': '电子邮件', 'value': record['email']},
    {'label': '身份证号', 'value': record['idCard']},
    {'label': '紧急联系姓名', 'value': record['emergencyContactName']},
    {'label': '紧急联系电话', 'value': record['emergencyContactPhone']},
    {'label': '所在部门', 'value': record['dept'] ? record['dept']['name'] : '暂未分配部门', 'span': 24},
    {'label': '员工岗位', 'value': record['job']},
    {'label': '入职日期', 'value': record['hiredate'], 'format': dateFormat},
    {'label': '家庭住址', 'value': record['address'], 'type': 'card', 'span': 24},
    {'label': '员工描述', 'value': record['info'], 'type': 'card', 'span': 24},
    {'label': '创建时间', 'value': record['created'], 'format': dateFormat},
    {'label': '修改时间', 'value': record['updated'], 'format': dateFormat},
  ];
  detailDrawer.value = true;
}

/* ==================== 单条添加 ==================== */
function insert() {
  router.push('/EmpInsert');
}

/* ==================== 单条修改 ==================== */
function update(row) {
  sessionStorage.setItem('emp', JSON.stringify(row));
  router.push('/EmpUpdate');
}

/* ==================== 单条删除 ==================== */
function remove(row) {
  myRemove({'id': row['id'], 'api': removeApi, 'fn': page});
}

/* ==================== 批量删除 ==================== */
// 批量删除主键数组
let ids = [];

function selectionChange(rows) {
  ids = rows.map(e => e['id']);
}

function removeBatch() {
  myRemoveBatch({'ids': ids, 'api': removeBatchApi, 'fn': page})
}

/* ==================== 按员工姓名模糊查询 ==================== */
function pageLikeName(val) {

  // 仅当输入框有值，或者当前处于按条件分页状态时，发送分页请求
  if (val || empName.value) {
    empName.value = val;
    page();
  }
}

/* ==================== 按电话号码精准查询 ==================== */
function pageByPhone(val) {

  // 仅当输入框有值，或者当前处于按条件分页状态时，发送分页请求
  if (val || empPhone.value) {
    empPhone.value = val;
    page();
  }
}

/* ==================== 按所在部门精准查询 ==================== */
function pageByDeptId(val) {
  // 仅当输入框有值，或者当前处于按条件分页状态时，发送分页请求
  if (val || empDeptId.value) {
    empDeptId.value = val;
    page();
  }
}

/* ==================== 重置密码 ==================== */
async function resetPassword(row) {

  // 危险操作保护
  if (!await elConfirm('是否要重置密码？')) return;

  let res = await resetPasswdApi(row['id']);
  let data = getResponseData(res);
  if (data) {
    ElMessage.success(`密码重置为手机后六位！`);
    // 若重置的是当前登录的员工，则跳入登录页面
    if (loginEmp['id'] === row['id']) {
      ElMessage.success('重置了当前登录的员工密码，请重新登录！');
      setTimeout(() => router.push('/'), 1000);
    }
    // 否则重新分页
    else {
      await page();
    }
  }
}

/* ==================== 查询全部的部门记录 ==================== */
let deptItems = [];

async function listDept() {
  let res = await listApi();
  let depts = getResponseData(res);
  Object.values(depts).forEach(dept => {
    deptItems.push({'label': dept['name'], 'value': dept['id']});
  });
}

/* ==================== 角色列表 ==================== */
function updateMyRoles(row) {
  sessionStorage.setItem('empId', row['id']);
  sessionStorage.setItem('empName', row['name']);
  router.push('/EmpUpdateRoles');
}

/* ==================== 头像地址 ==================== */
function minio(src) {
  return LOCAL_RES.value('../assets/image/logo.png');
  // return MINIO_HOST + '/avatar/' + src;
}

/* ==================== 打印报表 ==================== */
function excel() {
  // excelApi('/emp/excel', '员工统计表');
}

/* ==================== 加载函数 ==================== */
onMounted(() => {
  listDept();
  page();
});

</script>

<template>

  <my-nav :items="[
    {'icon': 'Avatar', 'label': '用户管理'},
    {'icon': 'User', 'label': '员工列表'},
  ]"/>

  <my-head :items="[
    {'type': 'ipt', 'span': 5, 'placeholder': '按员工姓名模糊搜索', 'fn': pageLikeName},
    {'type': 'ipt', 'span': 5, 'placeholder': '按电话号码精准搜索', 'fn': pageByPhone},
    {'type': 'opt', 'span': 5, 'placeholder': '按所在部门精准搜索', 'fn': pageByDeptId, 'optItems': deptItems},
    {'type': 'insertBtn', 'offset': 6, 'fn': insert},
    {'type': 'deleteBtn', 'fn': removeBatch},
    {'type': 'excelBtn', 'fn': excel},
  ]"/>

  <my-table v-if="records" :records="records" :columns="[
    {'column': ['员工信息', '员工头像'], 'property': 'avatar', 'type':'img', 'minio': minio, 'sortable': false, 'tooltip': false},
    {'column': ['员工信息', '员工编号'], 'property': 'eno', 'type':'tag', 'width': 100},
    {'column': ['员工信息', '员工姓名'], 'property': 'name', 'width': 100},
    {'column': ['部门信息', '所在部门'], 'property': 'dept.name', 'width': 120},
    {'column': ['部门信息', '员工岗位'], 'property': 'job', 'width': 120},
    {'column': ['部门信息', '入职日期'], 'property': 'hiredate', 'format': dateFormat, 'width': 150},
  ]" :buttons="[
    {'type': 'info', 'fn': detail},
    {'type': 'update', 'fn': update},
    {'type': 'delete', 'fn': remove},
    {'btnLabel': '重置密码', 'btnType': 'danger','btnIcon': 'delete', 'fn': resetPassword},
    {'btnLabel': '角色列表', 'btnType': 'warning','btnIcon': 'User', 'fn': updateMyRoles},
  ]" :selection-change="selectionChange"/>

  <my-pager v-if="records" :page-info="pageInfo"/>

  <el-drawer v-model="detailDrawer" size="50%">
    <my-list title="记录详情" :items="detailItems" column="2"/>
  </el-drawer>

</template>

<style scoped lang="scss">

</style>